Personal tools

Lua/Tutorials/Using events

From JC2-MP Documentation

< Lua‎ | Tutorials
Jump to: navigation, search

Simple usage

Events:Subscribe("SomeEventName", function)

This will print everything that is said into the console.

function MyFunction(args)
	print(args.player, args.text)
end
 
Events:Subscribe("PlayerChat", MyFunction)

There is a shorthand way to write this using an inline function:

Events:Subscribe("PlayerChat", function(args)
	print(args.player, args.text)
end)

Using classes

Events:Subscribe("SomeEventName", instance, function)

When using classes, your class instances will probably want to know when stuff happens. Instead of events calling a global function, you can give them an instance to call the function on. This is done by passing self to Events:Subscribe as the second argument.

Important: Make sure you store the subscribed event and call Events:Unsubscribe on it later. Simply removing any references to the class instance is not enough.

class("MyClass")
 
function MyClass:__init()
	self.event = Events:Subscribe("PlayerChat", self, self.MyFunction)end
 
function MyClass:OnPlayerChat(args)
	print(args.player, args.text)
end
 
-- Make sure to unsubscribe from events when you're done with the class!
function MyClass:CleanUpStuff()
	Events:Unsubscribe(self.event)
end